package com.itheima.controller;
 

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import com.aliyun.oss.model.*;

import java.io.*;
import java.util.Arrays;


/**
 * 文件上传与下载
 * @author jektong
 * @date 2022年05月13日 0:43
 */@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.oss.accessKey}")
    private String accessKey;
    @Value("${reggie.oss.secret}")
    private String secret;
    @Value("${reggie.oss.endpoint}")
    private String endpoint;

    @Value("${reggie.oss.bucketName}")
    private String bucketName;

    @Value("${reggie.oss.url}")
    private String fileBaseUrl;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException{
        System.out.println(endpoint);

        String fileName=file.getOriginalFilename();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secret);

        try {
            ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(file.getBytes()));
        } catch (OSSException oe) {
           log.error("上传文件异常");
        }  finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return new R<>(1,"上传成功",fileBaseUrl+"/"+fileName,null);
    }




    @GetMapping("/download")
    public R<String> download(@RequestParam(value = "name",required = false)String name) throws IOException{


        return new R<>(1,"下载成功",name,null);

    }




























}
